package com.wisnews.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wisnews.pojo.sec.entity.Operator;
import com.wisnews.service.sec.IRoleService;
import com.wisnews.service.sec.Impl.OperatorServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Objects;

/**
 * @description: 自定义userRealm
 * @param:
 * @return:
 * @author yuyd
 * @date: 2021/5/2 22:18
 */
public class UserRealm extends AuthorizingRealm {

	private static final transient Logger log = LoggerFactory.getLogger(AuthorizingRealm.class);

	@Autowired
	private OperatorServiceImpl operatorService;

	@Autowired
	private IRoleService roleService;

	// 授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		log.error("执行了=>授权 doGetAuthorizationInfo");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Subject currentUser = SecurityUtils.getSubject();
		// 拿到operator对象
		Operator operator = (Operator) currentUser.getPrincipal();
		//通过角色id获取权限信息
		String permissions = roleService.getJurisdiction4RoleId(operator.getOperatorRole());
		if (Objects.isNull(permissions)){
			return info;
		}
		String[] perlist = permissions.split(",");
		// 给用户赋权
		info.addStringPermissions(Arrays.asList(perlist));
		return info;
	}

	/**
	 * @description: 认证
	 * @param:
	 * @return:
	 * @author yuyd
	 * @date: 2021/5/2 22:18
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		log.error("执行了=>认证 doGetAuthenticationInfo");
		UsernamePasswordToken usertoken = (UsernamePasswordToken) token;
		//根据用户名查询
		LambdaQueryWrapper<Operator> queryWrapper = new LambdaQueryWrapper<Operator>().eq(Operator::getCode,usertoken.getUsername());
		Operator operator = operatorService.getOne(queryWrapper);
		if (ObjectUtils.isNull(operator)) {
			//根据邮箱查询
			LambdaQueryWrapper<Operator> lambdaQueryWrapper = new LambdaQueryWrapper<Operator>().eq(Operator::getEmail,usertoken.getUsername());
			operator = operatorService.getOne(lambdaQueryWrapper);
			if (ObjectUtils.isNull(operator)){
				throw new UnknownAccountException("账号不存在！");
			}
		}
		// 密码认证,shiro做了
		// 第一个参数传递用户的信息,就可以通过获取当前用户的getPrincipal获得
		return new SimpleAuthenticationInfo(operator, operator.getPassword(),new MyByteSource(operator.getSalt()),getName());
	}
}
